package io.p2p.stream.p2pmain.session;

import io.p2p.stream.p2pmain.node.StunNode;
import io.p2p.stream.p2pmain.task.StunNodeHeartbeatMonitorTask;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class StunNodeSessionManager {
    private static StunNodeSessionManager instance;

    private StunNodeSessionManager(){
        // 使用ScheduledExecutorService执行心跳检测任务
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(new StunNodeHeartbeatMonitorTask(deputyNodeMap), 0, 10, TimeUnit.SECONDS); // 每10秒执行一次
    }

    public static StunNodeSessionManager getInstance(){
        if(instance == null){
            synchronized (StunNodeSessionManager.class){
                if(instance == null) {
                    instance = new StunNodeSessionManager();
                }
            }
        }
        return instance;
    }

    private Map<String, StunNode> deputyNodeMap = new ConcurrentHashMap<>();

    public void pushBack(String key, StunNode node){
        deputyNodeMap.put(key,node);
    }

    public void remove(String ip,int port){
        Iterator<StunNode> it = deputyNodeMap.values().iterator();
        while(it.hasNext()){
            StunNode node = it.next();
            if(node.getIp().equals(ip) && node.getPort() == port){
                it.remove();
                break;
            }
        }
    }

    public StunNode find(String name){
        return deputyNodeMap.get(name);
    }

    public void flush(String name,String ip,int port){
        StunNode node = deputyNodeMap.get(name);
        if(node != null){
            node.setIp(ip);
            node.setName(name);
            node.setLastActiveTime(new Date());
        }else{
            StunNode newNode = new StunNode();
            newNode.setName(name);
            newNode.setIp(ip);
            newNode.setPort(port);
            newNode.setLastActiveTime(new Date());
            deputyNodeMap.put(name,newNode);
        }
    }

}
